import java.util.*;
import java.io.*;

class StudentInfoList {
    public class InputInfoErrorException extends Exception {
        public InputInfoErrorException(Throwable e) {
            super(e);
        }

        public InputInfoErrorException() {
            super();
        }
    }

    public class OutputException extends Exception {
        public OutputException(Throwable e) {
            super(e);
        }
    }

    static final private String DO_HAVE_STUDENT = "y";
    static final private String FILE_TITLE = "ID\t\tName\t\tAvgScore\r\n";
    private List<Student> infoList = null;

    public StudentInfoList() {
        infoList = new ArrayList<Student>();
    }

    public void getStudentInfoFromInput()  throws InputInfoErrorException {
        try {
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            while (DO_HAVE_STUDENT.equals(haveStudent(stdin))) {
                infoList.add(Student.parseString(stdin.readLine()));
            }
        } catch (IOException e) {
            System.out.println("Standard Input Error!");
            throw new InputInfoErrorException(e);
        } catch (Student.DataStringFormatException e) {
            System.out.println(e.getMessage());
            throw new InputInfoErrorException();
        }
    }

    private String haveStudent(BufferedReader stdin) throws IOException {
        System.out.println("Have student info to Input?");
        System.out.print("Yes(y) or No(n): ");
        return stdin.readLine();
    }

    public void printAverageInfoToFile(String path) throws OutputException {
        try {
            //prepare for the output file
            //if the file not exists, create it and its father path(if necessary)
            //if the file exists, append to write it
            File file = new File(path);
            FileWriter fw = null;
            if (file.exists()) {
                fw = new FileWriter(file, true);
            } else {
                File fatherDir = file.getParentFile();
                if (!fatherDir.exists()) {
                    fatherDir.mkdirs();
                }
                fw = new FileWriter(file);
                fw.write(FILE_TITLE, 0, FILE_TITLE.length());
            }

            for (Student student : infoList) {
                String avgString = student.makeAverageGradeInfo();
                fw.write(avgString + "\r\n", 0, avgString.length() + 2);
            }
            fw.flush();
            fw.close();
        } catch (IOException e) {
            System.out.println("Error occured when output!");
            throw new OutputException(e);
        }
    }

    public void printAverageInfoToStdout() {
        for (Student student : infoList) {
            System.out.println(student.makeAverageGradeInfo());
        }
    }
}
